<template>
  <div class="basic-setting">
    <ContentWrap>
      <div class="flex items-center justify-between header">
        <div class="flex items-center">
          <div>
            <span class="mr-4">区域代理</span>
            <el-switch v-model="switchValue" />
            <div class="text">开启后全局生效</div>
          </div>
          <div class="ml-4">
            <span>采购订单的</span>
            <el-input-number
              v-model="inputValue"
              style="width: 140px"
              :min="0"
                :max="100"
                controls-position="right"
              :disabled="!switchValue"
              placeholder="请输入"
            />%作为佣金
          </div>
        </div>
        <el-button type="primary" @click="saveBasic" :loading="saveloading"> 保存 </el-button>
      </div>
    </ContentWrap>
    <div class="mb-4">
      <el-radio-group v-model="setRadio">
        <el-radio-button label="基础设置" :value="2" />
        <el-radio-button label="分佣规则" :value="1" />
      </el-radio-group>
    </div>
    <ContentWrap>
      <div class="setBasic" v-if="setRadio === 2">
        <div>关联门店</div>
        <div class="commission-box">
          <div style="color: #c00; font-weight: bold">（佣金类型：关联门店拿货佣金）</div>
          <div class="flex items-center justify-between gap-2">
            所在地区门店拿货价
            <div>
              区域直属
              <el-input-number
                v-model="store.directRate"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 140px"
                controls-position="right"
                @change="handleInput('store', 'directRate')"
              />
              % 间属
              <el-input-number
                v-model="store.indirectRate"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 140px"
                controls-position="right"
                @change="handleInput('store', 'indirectRate')"
              />
              %
            </div>
          </div>
        </div>
        <el-radio-group v-model="commissionType">
          <el-radio :value="'register'">关联所在地区注册用户（选其一）</el-radio>
        </el-radio-group>
        <div class="commission-box">
          <div style="color: #c00; font-weight: bold">（佣金类型：注册佣金）</div>
          <div>注册在所在区域的用户下单</div>
          <div class="flex items-center justify-between gap-2">
            <div>
              按照商品毛利润进行统计
              <el-input-number
                v-model="register.sharePercent"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 80px"
                @change="handleInput('register', 'sharePercent')"
              />
              %
            </div>
            <div>
              区域直属
              <el-input-number
                v-model="register.directRate"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 80px"
                @change="handleInput('register', 'directRate')"
              />
              % 间属
              <el-input-number
                v-model="register.indirectRate"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 80px"
                @change="handleInput('register', 'indirectRate')"
              />
              %
            </div>
          </div>
        </div>

        <el-radio-group v-model="commissionType">
          <el-radio :value="'order'">关联所在地区下单用户（选其一）</el-radio>
        </el-radio-group>
        <div class="commission-box">
          <div style="color: #c00; font-weight: bold">（佣金类型：下单所在地区佣金）</div>
          <div>用户在所在区域门店下单</div>
          <div class="flex items-center justify-between gap-2">
            <div>
              按照商品毛利润进行统计
              <el-input-number
                v-model="order.sharePercent"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 80px"
                @change="handleInput('order', 'sharePercent')"
              />
              %
            </div>
            <div>
              区域直属
              <el-input-number
                v-model="order.directRate"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 80px"
                @change="handleInput('order', 'directRate')"
              />
              % 间属
              <el-input-number
                v-model="order.indirectRate"
                :min="0"
                :max="100"
                :controls="false"
                style="width: 80px"
                @change="handleInput('order', 'indirectRate')"
              />
              %
            </div>
          </div>
        </div>
      </div>
      <div class="setShare" v-else-if="setRadio === 1">
        <h4>到店服务分佣</h4>
        <div class="setShare-content">
          <span class="mr-4">冻结转余额时间</span>
          核销后
          <el-input-number
            :min="0"
            :max="100"
            :step="1"
            step-strictly
            v-model="mallNumber"
            style="width: 120px"
            controls-position="right"
          />天
        </div>
        <!-- 门店进货分佣 -->
        <!-- 冻结余额时间   进货单完成后 多少天 -->
        <h4>门店进货分佣</h4>
        <div class="setShare-content">
          <span class="mr-4">冻结余额时间</span>
          核销后
          <el-input-number
            :min="0"
            :max="100"
            :step="1"
            step-strictly
            v-model="storeNumber"
            style="width: 120px"
            controls-position="right"
          />天
        </div>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { CardTitle } from '@/components/Card'
import {
  saveOrUpdateAgentRegionConfigShare,
  getAgentUsersConfigRule,
  updateAgentUsersConfigRule,
  getAgentRegionConfigShare
} from '@/api/mall/agent/index'

// 定义 props
const props = defineProps<{
  info?: any
}>()

const stateInfo = reactive({
  switchValue: false,
  inputValue: 0,
  setRadio: 2,
  storeNumber: 0,
  mallNumber: 0,
  commissionType: 'register',
  store: {
    directRate: 0,
    indirectRate: 0
  },
  register: {
    sharePercent: 0,
    directRate: 0,
    indirectRate: 0
  },
  order: {
    sharePercent: 0,
    directRate: 0,
    indirectRate: 0
  },
  saveloading: false
})
const {
  switchValue,
  inputValue,
  setRadio,
  storeNumber,
  commissionType,
  store,
  register,
  order,
  mallNumber,
  saveloading
} = toRefs(stateInfo)
const saveBasicShare = async () => {
  var obj = { ...stateInfo.register }
  if (stateInfo.commissionType === 'register') {
    if (stateInfo.register.sharePercent > 100) {
      ElMessage.warning('商品毛利润不能大于100')
      return
    }
    if (stateInfo.register.directRate + stateInfo.register.indirectRate > 100) {
      ElMessage.warning('区域直属和间属之和不能大于100')
      return
    }
    obj = { ...stateInfo.register }
  } else if (stateInfo.commissionType === 'order') {
    if (stateInfo.order.sharePercent > 100) {
      ElMessage.warning('商品毛利润不能大于100')
      return
    }
    if (stateInfo.order.directRate + stateInfo.order.indirectRate > 100) {
      ElMessage.warning('区域直属和间属之和不能大于100')
      return
    }
    obj = { ...stateInfo.order }
  }

  var configs: any = []
  if (!stateInfo.switchValue) {
    configs = [
      {
        ruleType: 0,
        hasOpen: stateInfo.switchValue
      }
    ]
  } else {
    configs = [
      {
        ruleType: 0,
        hasOpen: stateInfo.switchValue,
        sharePercent: Number(stateInfo.inputValue),
      },
      {
        ruleType: 1,
        directRate: Number(stateInfo.store.directRate),
        indirectRate: Number(stateInfo.store.indirectRate)
      },
      {
        ruleType: stateInfo.commissionType == 'register' ? 2 : 3,
        sharePercent: Number(obj.sharePercent),
        directRate: Number(obj.directRate),
        indirectRate: Number(obj.indirectRate)
      }
    ]
  }

  await saveOrUpdateAgentRegionConfigShare({
    configs: configs,
    onlineOrderReceiveDays: stateInfo.mallNumber,
    storePurchaseCommissionDays: stateInfo.storeNumber
  })
 
  ElMessage.success('保存成功')
}

const saveBasic = async () => {
  if (!stateInfo.inputValue && stateInfo.switchValue) {
    ElMessage.warning('请输入佣金比例')
    return
  }
  if (stateInfo.store.directRate + stateInfo.store.indirectRate > 100) {
    ElMessage.warning('区域直属和间属之和不能大于100')
    return
  }
  saveloading.value = true
  try {
    await saveBasicShare()
    // if (stateInfo.setRadio === 1) {
    //   await saveSharerules()
    // } else {
    //   await saveBasicShare()
    // }
  } finally {
    saveloading.value = false
  }
}
const handleInput = (group: string, key: string) => {
  // 只保留数字，且最大100
  let val = Number(stateInfo[group][key])
  if (isNaN(val) || val < 0) val = 0
  if (val > 100) val = 100
  stateInfo[group][key] = val
}
const getConfig = async () => {
  const { onlineOrderReceiveDays, storePurchaseCommissionDays, configs } = await getAgentRegionConfigShare()
  stateInfo.mallNumber = onlineOrderReceiveDays || 0
  stateInfo.storeNumber = storePurchaseCommissionDays || 0
  
  // 检查configs是否存在且有数据
  if (configs && configs.length > 0) {
    stateInfo.switchValue = configs[0].hasOpen
    stateInfo.inputValue=configs.find(item=>item.ruleType==0)?.sharePercent || 0
    stateInfo.store.directRate=configs.find(item=>item.ruleType==1)?.directRate || 0
    stateInfo.store.indirectRate=configs.find(item=>item.ruleType==1)?.indirectRate || 0
    stateInfo.commissionType=configs.find(item=>item.ruleType==2)?.ruleType == 2 ? 'register' : 'order'
    stateInfo.register.sharePercent=configs.find(item=>item.ruleType==2)?.sharePercent || 0
    stateInfo.register.directRate=configs.find(item=>item.ruleType==2)?.directRate || 0
    stateInfo.register.indirectRate=configs.find(item=>item.ruleType==2)?.indirectRate || 0
    stateInfo.order.sharePercent=configs.find(item=>item.ruleType==3)?.sharePercent || 0
    stateInfo.order.directRate=configs.find(item=>item.ruleType==3)?.directRate || 0
    stateInfo.order.indirectRate=configs.find(item=>item.ruleType==3)?.indirectRate || 0
   
  } else {
    // 如果configs不存在或为空，设置默认值
    stateInfo.switchValue = false
    stateInfo.inputValue = 0
    
    // 设置其他默认值
    stateInfo.store.directRate = 0
    stateInfo.store.indirectRate = 0
    stateInfo.register.sharePercent = 0
    stateInfo.register.directRate = 0
    stateInfo.register.indirectRate = 0
    stateInfo.order.sharePercent = 0
    stateInfo.order.directRate = 0
    stateInfo.order.indirectRate = 0
  }
}
onMounted(async () => {
  getConfig()
})
// 添加默认导出
defineOptions({
  name: 'BasicSetting'
})
</script>

<style scoped lang="scss">
.basic-setting {
  height: 100%;
  .header {
    font-size: 14px;
    .text {
      font-size: 10px;
      color: #999;
    }
  }
  .setBasic {
    font-size: 14px;
    &-content {
      margin: 20px;
    }
  }
  .setShare {
    font-size: 14px;
    &-content {
      margin: 20px;
    }
  }
}
.ml-2 {
  margin-left: 8px;
}
.commission-box {
  background: #f6f6f6;
  padding: 16px;
  margin-bottom: 24px;
  border-radius: 4px;
}
</style> 
